package com.gorkr.labuladong.data_struct.bt;

import org.junit.jupiter.api.Test;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author gorkr
 * @date 2022/07/25 20:42
 **/
public class M102BinaryTreeLevelOrderTraversal {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root==null){
            return new LinkedList<>();
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        LinkedList<TreeNode> item = new LinkedList<>();
        LinkedList<Integer> resItem = new LinkedList<>();
        List<List<Integer>> res = new LinkedList<>();
        while (!queue.isEmpty()){
            if(queue.peek()==null){
                queue.poll();
            }

            resItem.add(queue.peek().val);
            item.add(queue.poll());
            if(queue.isEmpty()){
                for (TreeNode node :
                        item) {
                    if(node.left!=null){
                        queue.add(node.left);
                    }
                    if(node.right!=null){
                        queue.add(node.right);
                    }
                }
                res.add(( LinkedList<Integer>)resItem.clone());
                item.clear();
                resItem.clear();
            }
        }
        return res;
    }

    public List<List<Integer>> levelOrder2(TreeNode root){

        Queue<TreeNode> queue = new LinkedList<>();
        LinkedList<Integer> level = new LinkedList<>();
        List<List<Integer>> res = new LinkedList<>();


        if(root!=null){
            queue.add(root);
        }
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                assert queue.peek() != null;
                level.add(queue.peek().val);

                TreeNode poll = queue.poll();
                if(poll.left!=null){
                    queue.add(poll.left);
                }
                if(poll.right!=null){
                    queue.add(poll.right);
                }
            }
            res.add((List<Integer>) level.clone());
            level.clear();
        }
        return res;

    }

    @Test
    public void test(){
        TreeNode treeNode = new TreeNode(3);
        treeNode.left = new TreeNode(9);
        treeNode.right = new TreeNode(20);
        treeNode.right.left = new TreeNode(15);
        treeNode.right.right = new TreeNode(7);
        List<List<Integer>> lists = levelOrder2(treeNode);
        System.out.println(lists.stream().toArray());


    }

}
    